package com.www.applyword.ui.my;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;

import androidx.core.content.FileProvider;

import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.TIMUserProfile;
import com.www.applyword.Constants.Constants;
import com.www.applyword.R;
import com.www.applyword.base.BaseActivity;
import com.www.applyword.bean.LoginBean;
import com.www.applyword.event.EventConstants;
import com.www.applyword.event.MessageEvent;
import com.www.applyword.http.CallBack;
import com.www.applyword.http.HttpClient;
import com.www.applyword.utils.ImageUtil;
import com.www.applyword.utils.PhotoUtil;
import com.www.applyword.utils.PhotoUtils;
import com.www.applyword.utils.SPUtil;
import com.www.applyword.utils.Utils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

import static com.www.applyword.ui.my.PersonalActivity.CODE_CAMERA_REQUEST;
import static com.www.applyword.ui.my.PersonalActivity.CODE_GALLERY_REQUEST;
import static com.www.applyword.ui.my.PersonalActivity.CODE_RESULT_REQUEST;

/**
 * author : huang
 * date   : 2019/11/22 0022 16:35
 * version: 1.0
 */
public class MyUserInfoActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.civ_head_photo2)
    CircleImageView civHeadPhoto;
    @BindView(R.id.ll_head_photo)
    LinearLayout llHeadPhoto;
    @BindView(R.id.et_name)
    EditText etName;
    private boolean flag;
    private Dialog dialog, dialogHead;
    private Uri imageUri;
    private Uri cropImageUri;
    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");
    private String string;

    private static int OUTPUT_X = 480;
    private static int OUTPUT_Y = 480;

    private PhotoUtils photoUtils;
    private String url2;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.my_info_activity);
        setTitle("修改个人信息");
        setRringTitle("提交");
        string = SPUtil.getString(Constants.NAME);
        etName.setText(string);
        etName.setSelection(string.length());
      //  String photo = SPUtil.getString(Constants.PHOTO);
        String url =  getIntent().getStringExtra("url");
        if (!TextUtils.isEmpty(url))ImageUtil.setImage(civHeadPhoto,url);
        tv_right.setOnClickListener(v -> {
            /*if (TextUtils.isEmpty(etName.getText().toString().trim())){
                Utils.showToastSafe("昵称不能为空");
                return;
            }*/

           /* if (flag && string.equals(etName.getText().toString().trim())) {
                Utils.showToastSafe("请上传个人头像或修改昵称");
                return;
            }*/

            if (flag) {
                HttpClient.postImg(MyUserInfoActivity.this, Constants.UPLOADUSERHEADIMAGE, fileCropUri, new CallBack<List<String>>() {
                    @Override
                    public void onSuccess(List<String> list) {
                        url2 = list.get(0);
                        Map<String, Object> params = new HashMap<>();
                        params.put("UserID", SPUtil.getString(Constants.USERID));
                        params.put("NikeName", etName.getText().toString().trim());
                        params.put("HeadImg", url2);
                        HttpClient.get(MyUserInfoActivity.this, Constants.UPDATEUSERNIKENAMEANDHEADIMG, params, new CallBack<LoginBean>() {
                            @Override
                            public void onSuccess(LoginBean result) {
                                HashMap<String, Object> hashMap = new HashMap<>();
                                // 头像，mIconUrl 就是您上传头像后的 URL，可以参考 Demo 中的随机头像作为示例
                                if (!TextUtils.isEmpty(Constants.HOST + url2)) {
                                    hashMap.put(TIMUserProfile.TIM_PROFILE_TYPE_KEY_FACEURL, Constants.HOST + url2);
                                }
                                TIMFriendshipManager.getInstance().modifySelfProfile(hashMap, new TIMCallBack() {
                                    @Override
                                    public void onError(int i, String s) {
                                       // ToastUtil.toastShortMessage("Error code = " + i + ", desc = " + s);
                                    }
                                    @Override
                                    public void onSuccess() {
                                        MessageEvent messageEvent = new MessageEvent();
                                        messageEvent.setMessageKey(EventConstants.REAL_NAME);
                                        EventBus.getDefault().post(messageEvent);
                                        Utils.showToastSafe("修改成功");
                                        finish();
                                       // DemoLog.i(TAG, "modifySelfProfile success");
                                    }
                                });
                            }
                        });
                    }
                });
            }else {
                Map<String, Object> params = new HashMap<>();
                params.put("UserID", SPUtil.getString(Constants.USERID));
                params.put("NikeName", etName.getText().toString().trim());
                params.put("HeadImg", SPUtil.getString(Constants.PHOTO));
                HttpClient.get(MyUserInfoActivity.this, Constants.UPDATEUSERNIKENAMEANDHEADIMG, params, new CallBack<LoginBean>() {
                    @Override
                    public void onSuccess(LoginBean result) {
                        MessageEvent messageEvent = new MessageEvent();
                        messageEvent.setMessageKey(EventConstants.REAL_NAME);
                        EventBus.getDefault().post(messageEvent);
                        Utils.showToastSafe("修改成功");
                        finish();
                    }
                });
            }
        });
    }

    @Override
    protected void loadData() {
        photoUtils = new PhotoUtils(new PhotoUtils.OnPhotoResultListener() {
            @Override
            public void onPhotoResult(Uri uri) {
                //或者是通过glide框架
                Bitmap bitmap = PhotoUtil.getBitmapFromUri(uri, MyUserInfoActivity.this);
                if (bitmap != null) {
                    flag = true;
                    civHeadPhoto.setImageBitmap(bitmap);
                }
            }

            @Override
            public void onPhotoResult2(String uri) {

            }
            @Override
            public void onPhotoCancel() {

            }
        });
    }



    @OnClick({R.id.civ_head_photo2, R.id.et_name})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.civ_head_photo2:
                showHeadDialog();
                break;
            case R.id.et_name:

                break;
                default:
        }
    }

    private void showHeadDialog() {
        dialogHead = new Dialog(this, R.style.ActionSheetDialogStyle);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_head_portrait, null);
        view.findViewById(R.id.dialog_shoot).setOnClickListener(this);
        view.findViewById(R.id.dialog_photo_album).setOnClickListener(this);
        view.findViewById(R.id.dialog_cancel).setOnClickListener(this);
        dialogHead.setContentView(view);
        Window window = dialogHead.getWindow();
        if (window == null) {
            return;
        }
        dialogHead.show();//显示对话框//设置Dialog从窗体底部弹出
        window.setGravity(Gravity.BOTTOM);
        //获取窗体的属性
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.y = 20;//设置Dialog距离底部的距离
        //将属性设置给窗体
        window.setAttributes(lp);

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.dialog_shoot://拍摄
                imageUri = Uri.fromFile(fileUri);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    imageUri = FileProvider.getUriForFile(this, "com.whmnrc.parttimejob.FileProvider", fileUri);
                }
                PhotoUtil.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
             //   photoUtils.takePicture(MyUserInfoActivity.this);
                dialogHead.dismiss();

                break;
            case R.id.dialog_photo_album://相册
                PhotoUtil.openPic(this, CODE_GALLERY_REQUEST);
               // photoUtils.takePicture(MyUserInfoActivity.this);
              //  photoUtils.selectPicture(MyUserInfoActivity.this);
                dialogHead.dismiss();
                break;

            case R.id.dialog_cancel://取消
                dialogHead.dismiss();
                break;

            default:
        }
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CODE_CAMERA_REQUEST:
                    cropImageUri = Uri.fromFile(fileCropUri);
                    PhotoUtil.cropImageUri(this, imageUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
                    break;
                case CODE_GALLERY_REQUEST:
                    cropImageUri = Uri.fromFile(fileCropUri);
                    Uri newUri = Uri.parse(PhotoUtil.getPath(this, intent.getData()));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        newUri = FileProvider.getUriForFile(this, "com.whmnrc.parttimejob.FileProvider", new File(newUri.getPath()));
                    }
                    PhotoUtil.cropImageUri(this, newUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
                    break;
                case CODE_RESULT_REQUEST:
                   // Bitmap bitmap = BitmapFactory.decodeFile(cropImageUri.getPath());
                   Bitmap bitmap = PhotoUtil.getBitmapFromUri(cropImageUri, this);
                    if (bitmap != null) {
                        flag = true;
                        civHeadPhoto.setImageBitmap(bitmap);
                    }
                    break;
                default:
            }
        }

        super.onActivityResult(requestCode, resultCode, intent);
    }
}
